package com.doge.calcalbum.business.note

import com.doge.calcalbum.utils.closeQuietly
import com.doge.calcalbum.utils.isMainThread
import java.io.*
import java.nio.charset.StandardCharsets

object NoteUtils {
    fun write(content: String, output: File) {
        require(!isMainThread())
        val stream = FileOutputStream(output, false)
        val outputStream = OutputStreamWriter(stream, StandardCharsets.UTF_8)
        val writer = BufferedWriter(outputStream)
        try {
            writer.append(content)
            writer.append("\n")
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            closeQuietly(writer)
            closeQuietly(outputStream)
            closeQuietly(stream)
        }
    }

    fun read(input: File): String {
        require(!isMainThread())
        val stream = FileInputStream(input)
        val inputStream = InputStreamReader(stream, StandardCharsets.UTF_8)
        val reader = BufferedReader(inputStream)
        val stringBuilder = StringBuilder()
        var line: String?
        try {
            while (reader.readLine().also { line = it } != null) {
                stringBuilder.append(line)
                stringBuilder.append("\n")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            closeQuietly(reader)
            closeQuietly(inputStream)
            closeQuietly(stream)
        }
        return stringBuilder.toString()
    }
}